package com.bearsadmin.config;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.MultipartConfigElement;
import java.io.File;

/**
 * 文件上传配置
 *
 * @author Bears Admin
 * @since 1.0.0
 */
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {

    /**
     * 文件上传路径
     */
    public static final String UPLOAD_PATH = System.getProperty("user.dir") + "/uploads/";

    /**
     * 头像上传路径
     */
    public static final String AVATAR_PATH = UPLOAD_PATH + "avatars/";

    /**
     * 初始化上传目录
     */
    @PostConstruct
    public void initUploadDirectories() {
        File uploadDir = new File(UPLOAD_PATH);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        File avatarDir = new File(AVATAR_PATH);
        if (!avatarDir.exists()) {
            avatarDir.mkdirs();
        }

        System.out.println("上传目录初始化完成:");
        System.out.println("Upload Path: " + UPLOAD_PATH);
        System.out.println("Avatar Path: " + AVATAR_PATH);
    }

    /**
     * 配置文件上传
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个文件最大 10MB
        factory.setMaxFileSize(DataSize.ofMegabytes(10));
        // 总文件大小最大 50MB
        factory.setMaxRequestSize(DataSize.ofMegabytes(50));
        return factory.createMultipartConfig();
    }

    /**
     * 配置静态资源访问
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + UPLOAD_PATH);
    }
}